package com.abel.bigwater.kmgw.impl

import com.abel.bigwater.dataserver.model.ServiceConfig
import com.abel.bigwater.kmgw.dao.ConfigDao
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.mongodb.core.query.isEqualTo
import org.springframework.stereotype.Repository

@Repository
class ConfigDaoImpl : ConfigDao {

    @Autowired
    var mongoTemplate: MongoTemplate? = null

    /**
     * retrieve service-config by cfg-id.
     */
    override fun getConfig(cfgId: String): ServiceConfig? =
            mongoTemplate?.find(Query().addCriteria(Criteria.where("cfgId").isEqualTo(cfgId)),
                    ServiceConfig::class.java)?.firstOrNull()

    override fun createConfig(cfg: ServiceConfig): Int? {
        mongoTemplate?.save(cfg)

        return 1
    }

    override fun deleteConfig(cfgId: String): Long {
        val result = mongoTemplate?.remove(Query().addCriteria(Criteria.where("cfgId").isEqualTo(cfgId)),
                ServiceConfig::class.java)

        return result?.deletedCount ?: 0
    }
}